package com.yjt.fresh.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yjt.fresh.R;
import com.yjt.fresh.ZFHelper;
import com.yjt.fresh.activity.AtyLogin;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.lisenter.ZFConnectionListener;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.utils.ZFNetUtils;

import butterknife.ButterKnife;

/**
 * 所有的activity父类
 *
 * @author Gxcheng
 * @time 2016/11/1 0001 8:51
 */
public abstract class BaseSimpleActivity extends RxAppCompatActivity {
    protected static final int LOGIN_REQUEST_CODE = 1008;
    protected Activity mContext;
    protected Toolbar mToolbar;
    protected boolean mShowSearchBar = false;
    protected int mPageIndex = 1;
    protected int mPageSize = 10;
    protected int mPageCount;//总页数
    //经度 108.394825*/
    protected double mLatitude;
    //纬度  22.878034*/
    protected double mLongitude;
    protected boolean mIsNetWork=true;

    //条件搜索布局
    protected LinearLayout mSearchLlt;
    protected ImageView mSearchArrowIv;
    protected TextView mSearchTextTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId=getContentView();
        setContentView(layoutId);
        ButterKnife.bind(this);
        this.mContext = this;
//        ActivityStackControlUtil.add(mContext);
        /*添加网络状态监听*/
        ZFHelper.getInstance().addConnectionListener(connectionListener);
        /*设置toolbar*/
//        setToolbar();
        initViews();
        initEvent();
//        mMapLocationUtils=new MapLocationUtils(mContext);
//        mMapLocationUtils.setOnLocationListenner(this);

    }

    /**
     * 设置toolbar
     *
     * @author Gxcheng
     * @time 2016/11/1 0001 10:30
     */
    protected void setToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setHomeButtonEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 设置toolbar返回样式
     *
     * @author Gxcheng
     * @time 2016/11/1 0001 10:31
     */
    protected void setToolbarBack() {
         /* Navigation Icon 要設定在 setSupoortActionBar 才有作用 否則會出現 back button*/
        mToolbar.setNavigationIcon(R.mipmap.icon_back);
    }

    /**
     * 设置标题
     *
     * @author Gxcheng
     * @time 2016/11/1 0001 10:31
     */
    protected void setToolbarTitle(String title) {
        TextView mToolbarTitle = (TextView) findViewById(R.id.toolbar_title_tv);
        mToolbarTitle.setVisibility(View.VISIBLE);
        mToolbarTitle.setText(title);
    }

    /**
     * 设置toolbar右边文字按钮
     *
     * @param right
     */
    protected TextView setToolbarRight(String right) {
        TextView mToolbarRight = (TextView) findViewById(R.id.toolbar_right_tv);
        mToolbarRight.setVisibility(View.VISIBLE);
        mToolbarRight.setText(right);
        return mToolbarRight;
    }

    /**
     * 设置toolbar右边文字按钮
     *
     */
    protected TextView setToolbarRightIcon(int resId) {
        TextView mToolbarRight = (TextView) findViewById(R.id.toolbar_right_add_tv);
        mToolbarRight.setVisibility(View.VISIBLE);
        Drawable drawable= ContextCompat.getDrawable(mContext,resId);
        drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
        mToolbarRight.setCompoundDrawables(drawable,null,null,null);
        return mToolbarRight;
    }

    protected EditText getSearchEt(){
        TextView mToolbarTitle = (TextView) findViewById(R.id.toolbar_title_tv);
        mToolbarTitle.setVisibility(View.GONE);
        TextView mToolbarRight = (TextView) findViewById(R.id.toolbar_right_tv);
        mToolbarRight.setVisibility(View.VISIBLE);
        findViewById(R.id.toolbar_right_add_tv).setVisibility(View.GONE);
        mToolbarRight.setText("取消");
        EditText editText=getViewById(R.id.toolbar_search_et);
        editText.setVisibility(View.VISIBLE);
        return editText;
    }

    /**
     * 设置toolbar右边文字按钮
     *
     * @param right
     */
    protected TextView setToolbarRightAdd(String right) {
        TextView mToolbarRight = (TextView) findViewById(R.id.toolbar_right_add_tv);
        mToolbarRight.setVisibility(View.VISIBLE);
        mToolbarRight.setText(right);
        return mToolbarRight;
    }



    /*
     * 描述：拨打电话拨号界面
     * 作者：gxcheng
     * 日期：2017/2/8 0008 15:32
    */
    protected void showMobileDialerInterface(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (getPackageManager().resolveActivity(intent, 0) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(mContext, "您的设备没有拨号应用", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 将toolbar右边的文字隐藏掉
     */
    protected void hideToolbarRight() {
        TextView mToolbarRight = (TextView) findViewById(R.id.toolbar_right_tv);
        mToolbarRight.setVisibility(View.GONE);
    }

    /*获取textview*/
    protected TextView getTextViewById(int resId){
        return getViewById(resId);
    }

    protected EditText getEditTextById(int resId){
        return (EditText) findViewById(R.id.toolbar_search_et);
    }

//    protected void setNoResult(boolean isShow){
//        if (isShow){
//            findViewById(R.id.view_no_result).setVisibility(View.VISIBLE);
//        }else {
//            findViewById(R.id.view_no_result).setVisibility(View.GONE);
//        }
//    }


    //用于点击其他地方时隐藏软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    /**
     * 点击其他地方隐藏软键盘
     *
     * @param v
     * @param event
     * @return
     */
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    /**
     * description: 注册并发送本地广播，登录和退出登录的时候通知ui刷新
     * autour: gxcheng
     * date: 2018/2/9 23:29
     */
    /**
     * type,操作类型，0登录，1退出登录
     */
    protected LocalBroadcastManager localBroadcastManager;
    protected void registerAndSendBroadcast(int type){
        Intent intent = new Intent(MyConstants.LOGIN_LOCAL_BROADCAST);
        intent.putExtra(MyConstants.JUMP_TYPE,type);
        localBroadcastManager=LocalBroadcastManager.getInstance(mContext);
        //发送本地广播
        localBroadcastManager.sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (localBroadcastManager!=null){
            localBroadcastManager=null;
        }

    }
    protected boolean getNetState(){
        return ZFNetUtils.hasNetwork(mContext);
    }

    /**
     * 跳转
     *
     * @param activityClass
     */
    public void startActivity(Class activityClass) {
        startActivity(activityClass, null);
    }

    public void startActivity(Class activityClass, Bundle bundle) {
        Intent intent = new Intent(this, activityClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void startActivityForResult(Class activityClass, int requestCode) {
        startActivityForResult(activityClass, null, requestCode);
    }

    public void startActivityForResult(Class activityClass, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, activityClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }


    protected void toLogin(){
        Intent intent = new Intent(mContext, AtyLogin.class);
        startActivityForResult(intent, LOGIN_REQUEST_CODE);
    }

    /**
     * 查找View
     *
     * @param id   控件的id
     * @param <VT> View类型
     * @return
     */
    protected <VT extends View> VT getViewById(@IdRes int id) {
        return (VT) findViewById(id);
    }

    /*
     * 描述：监听网络状态
     * 作者：gxcheng
     * 日期：2017/3/18 0018 15:26
    */
    private ZFConnectionListener connectionListener = new ZFConnectionListener() {
        @Override
        public void onConnected() {
            onConnectionConnected();
            Log.e("tag", "onConnected: ");
        }

        @Override
        public void onDisconnected(int error) {
            onConnectionDisconnected();
            PreferenceManager.getInstance().setSaIsNet(false);
            Log.e("tag", "onDisconnected: ");
        }
    };

    /**
     * connected to server
     */
    protected void onConnectionConnected() {
        ZFHelper.getInstance().setIsNetworkAble(true);
    }

    /**
     * disconnected with server
     */
    protected void onConnectionDisconnected() {
        ZFHelper.getInstance().setIsNetworkAble(false);
    }

    /*获取xml布局*/
    protected int getContentView() {
        return 0;
    }

    protected abstract void initViews();

    protected abstract void initEvent();



    protected View getPageViews(String url){
        ImageView imageView = new ImageView(this);
        imageView.setImageBitmap(BitmapFactory.decodeFile(url));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return imageView;
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 10010:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                } else {
                    // 没有获取到权限，做特殊处理
                    Toast.makeText(getApplicationContext(), "获取位置权限失败，请手动开启", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

}
